package com.kczd.activity;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.kczd.client.R;
import com.kczd.entity.Driver;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.ObjectSaveUtil;
import com.kczd.util.SysApplication;
import com.kczd.view.AlertIosDialog;
import com.kczd.view.CircleImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HeadsetActivity extends AppCompatActivity implements View.OnClickListener{
    private ImageView iv_back;
    private ImageView iv_finish;
    private CircleImageView iv_head;
    private EditText et_username;
    private EditText et_company;
    private EditText et_age;
    private EditText et_selfsign;
    private RelativeLayout view_safe;
    private RadioGroup rg_sex;
    private RelativeLayout head_layout;

    private String sex= Common.user.getSex();

    SweetAlertDialog pDialog = null;
    private  Bitmap bitmap = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_headset);
        setview();
        // 多activity管理
        SysApplication.getInstance().addActivity(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.personal, menu);
        return true;
    }

    private void setview() {
        iv_back=(ImageView) findViewById(R.id.iv_back);
        iv_finish=(ImageView) findViewById(R.id.iv_finish);
        iv_head=(CircleImageView) findViewById(R.id.iv_head);
        head_layout= (RelativeLayout) findViewById(R.id.head_layout);
        et_username=(EditText) findViewById(R.id.et_username);
        et_company=(EditText) findViewById(R.id.et_company);
        et_age=(EditText) findViewById(R.id.et_age);
        et_selfsign=(EditText) findViewById(R.id.et_selfsign);
        view_safe=(RelativeLayout) findViewById(R.id.view_safe);
        rg_sex=(RadioGroup) findViewById(R.id.rg_sex);

        mWH = (int) (getResources().getDisplayMetrics().density * mWH);

        pDialog = new SweetAlertDialog(this, SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);

        view_safe.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_finish.setOnClickListener(this);
        head_layout.setOnClickListener(this);

        String uImage ="http://www.dafuw.com/itf/uploadfile/"+Common.user.getDriver_img();
        //显示图片的配置
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.mipmap.img_loading)
                .showImageOnFail(R.mipmap.img_fail)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
        ImageLoader.getInstance().displayImage(uImage, iv_head, options);
        et_username.setText(Common.user.getUsername().contains("null")?"":Common.user.getUsername());
        et_company.setText(Common.user.getCompany().contains("null")?"":Common.user.getCompany());
        et_age.setText(Common.user.getBirthday().contains("null")?"":Common.user.getBirthday());
        et_selfsign.setText(Common.user.getSelf_sign().contains("null")?"":Common.user.getSelf_sign());
        if(sex.equals(Common.sex_man))
        {
            rg_sex.check(R.id.radioBtn1);
        }else{
            rg_sex.check(R.id.radioBtn2);
        }
        // 注册事件
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radioBtn1:
                        sex="1";
                        break;
                    case R.id.radioBtn2:
                        sex="2";
                        break;
                }
            }
        });
    }

    public boolean subpre(){
        return true;
    }
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.iv_finish:
                if(!subpre()){
                    new AlertDialog.Builder(this).setIcon(android.R.drawable.btn_star)
                            .setTitle("提交认证").setMessage("表单不全")
                            .setPositiveButton("确定",new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog,int which) {
                                }
                            })  .show();
                    return;
                }else{
                    pDialog.show();
                    new Thread(){
                        @Override
                        public void run()
                        {
                            saveSelfInfo();
                        }
                    }.start();
                }

                break;

            case R.id.head_layout:
                showPopupWindow();//更换头像
                break;

            case R.id.view_safe:
                startActivity(new Intent(this, AcountSafeActivity.class));//忘记密码页面
                break;

            case R.id.iv_back:
                this.finish();
                break;

            default:
                break;
        }
    }
    //=========================================================================================================
    // 头像上传
    private static final int CAMERA_REQUEST_CODE = 222;
    private static final int PICTURE_REQUEST_CODE = 444;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static String uploadImageUrl = "http://www.dafuw.com/itf/tx_upload_file.php";
    private int mWH = 90;// 单位dp
    private String picPath ="";

    public void showPopupWindow() {
        new AlertIosDialog(this).builder(R.style.ActionListDialogStyle).setAlertDialogSize(1).setSelsctPanel(R.drawable.camera,R.drawable.picture,
                "相机","相册").setLeftPanelOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 请求拍照的Action
                // 在onActivityResult中处理拍照结果
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
            }
        }).setRightPanelOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        // 相册
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, PICTURE_REQUEST_CODE);
            }
        }).setCanaleBtnClickListener("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        }).show();

    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null)
        {
            Uri uri = data.getData();
            if (null != uri)
            {
                String imgPath = null;
                ContentResolver resolver = this.getContentResolver();
                String[] columns = { MediaStore.Images.Media.DATA };
                Cursor cursor = null;
                cursor = resolver.query(uri, columns, null, null, null);
                if (Build.VERSION.SDK_INT > 18)// 4.4以后文件选择发生变化，判断处理
                {
                    // http://blog.csdn.net/tempersitu/article/details/20557383
                    if (requestCode == PICTURE_REQUEST_CODE)// 选择图片
                    {
                        imgPath = uri.getPath();
                        if (!TextUtils.isEmpty(imgPath)
                                && imgPath.contains(":"))
                        {
                            String imgIndex = imgPath.split(":")[1];
                            cursor = resolver.query(
                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                    columns, "_id=?", new String[] { imgIndex },
                                    null);
                        }
                    }
                }
                if (null != cursor && cursor.moveToFirst())
                {
                    int columnIndex = cursor.getColumnIndex(columns[0]);
                    imgPath = cursor.getString(columnIndex);
                    cursor.close();
                }
                if (!TextUtils.isEmpty(imgPath))
                {
                    bitmap = genBitmap(imgPath);
                }
            }
            else if (requestCode == CAMERA_REQUEST_CODE)// 拍照
            {
                // 拍照时，注意小米手机不会保存图片到本地，只可以从intent中取出bitmap, 要特殊处理
                Object object = data.getExtras().get("data");
                if (null != object && object instanceof Bitmap)
                {
                    bitmap = (Bitmap) object;
                }
            }
            if (null != bitmap)
            {
                pDialog.show();
                iv_head.setImageBitmap(bitmap);
                new Thread(){
                    @Override
                    public void run()
                    {
                        //上传头像到服务器
                        uploadHeadImage(bitmap, uploadImageUrl) ;
                    }
                }.start();
            }
        }
    }

    private void uploadHeadImage(Bitmap bm, String uploadImageUrl) {
        OkHttpClient client=new OkHttpClient();
        ByteArrayOutputStream stream=new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG,60,stream);
        byte[] bytes=stream.toByteArray();
        String img=new String(Base64.encodeToString(bytes,Base64.DEFAULT));
        RequestBody requestBody=new FormBody.Builder()
                .add("img",img)
                .build();
        Request request=new Request.Builder()
                .url(uploadImageUrl)
                .post(requestBody)
                .build();
        Response response= null;
        try {
            response = client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            uploadHandle.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler uploadHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                pDialog.dismiss();
                jsonResult = new JSONObject(val);
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    picPath = jsonResult.getString("uploadPath");
                    Toast.makeText(HeadsetActivity.this, "上传成功", Toast.LENGTH_SHORT).show();

                }else{
                    Toast.makeText(HeadsetActivity.this, "异常："+jsonResult.toString(),
                            Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    /**通过给定的图片路径生成对应的bitmap*/
    private Bitmap genBitmap(String imgPath)
    {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imgPath, options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        int widthSample = (int) (imageWidth / mWH);
        int heightSample = (int) (imageHeight / mWH);
        // 计算缩放比例
        options.inSampleSize = widthSample < heightSample ? heightSample
                : widthSample;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(imgPath, options);
    }

    String url = Common.net_addr + "itf/tx_set_selfinfo_page.php";
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                pDialog.dismiss();
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    Common.user.setUkey(jsonResult.getString("ukey"));
                    Common.user.setUsername(et_username.getText().toString().contains("null")?"":et_username.getText().toString());
                    Common.user.setCompany(et_company.getText().toString().contains("null")?"":et_company.getText().toString());
                    Common.user.setBirthday(et_age.getText().toString());
                    Common.user.setSelf_sign(et_selfsign.getText().toString().contains("null")?"":et_selfsign.getText().toString());
                    Common.user.setSex(sex);
                    Common.user.setDriver_img(picPath.equals("")?Common.user.getDriver_img():picPath);
                    ObjectSaveUtil.saveObject(getBaseContext(), Common.user);

                    Toast.makeText(HeadsetActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    HeadsetActivity.this.finish();
                }else{
                    Toast.makeText(HeadsetActivity.this, "修改失败："+jsonResult.getString("err"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 保存个人信息的页面
     */
    public void saveSelfInfo() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("ukey", Common.user.getUkey())
                .add("utype", Common.utype)
                .add("head_img", picPath)
                .add("username", et_username.getText().toString())
                .add("sex", sex)
                .add("birthday", et_age.getText().toString())
                .add("company", et_company.getText().toString())
                .add("self_sign", et_selfsign.getText().toString())
                .build();
        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            handler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
